package com.guoxin.part4.chapter24;

import com.guoxin.part1.chapter8.BasicThreadPool;
import com.guoxin.part1.chapter8.ThreadPool;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author guoxin
 * @date 2019/9/2
 */
public class CharServer {
    private final int port;
    private ThreadPool threadPool;
    private ServerSocket serverSocket;

    public CharServer(int port) {this.port = port;}

    public CharServer() {
        this(13312);
    }

    public void startServer() throws IOException {
        this.threadPool = new BasicThreadPool(1, 4, 2, 1000);
        this.serverSocket = new ServerSocket(port);
        this.serverSocket.setReuseAddress(true);
        System.out.println("Chat server is started and listen at port: " + port);
        this.listen();

    }

    private void listen() throws IOException {
        for (; ; ) {
            Socket client = serverSocket.accept();
            this.threadPool.execute(new ClientHandler(client));
        }
    }
}
